package org.anyin.gitee.cloud.center.cdms.service.impl;

import org.anyin.gitee.cloud.center.cdms.convert.CsInfoConvert;
import org.anyin.gitee.cloud.center.cdms.model.CsInfo;
import org.anyin.gitee.cloud.center.cdms.model.CsWxInfo;
import org.anyin.gitee.cloud.center.cdms.repository.CsInfoRepository;
import org.anyin.gitee.cloud.center.cdms.repository.CsWxInfoRepository;
import org.anyin.gitee.cloud.center.cdms.service.CsInfoService;
import org.anyin.gitee.cloud.center.cdms.service.dto.CsInfoRegisterDTO;
import org.anyin.gitee.cloud.center.cdms.service.dto.CsWxInfoDTO;
import org.anyin.gitee.cloud.lib.core.enums.DelFlgEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CsInfoServiceImpl implements CsInfoService {

    @Autowired
    private CsInfoRepository csInfoRepository;

    @Autowired
    private CsWxInfoRepository csWxInfoRepository;

    @Autowired
    private CsInfoConvert csInfoConvert;

    @Override
    @Transactional(rollbackFor = Throwable.class, timeout = 60)
    public CsWxInfoDTO register(CsInfoRegisterDTO param) {
        CsInfo info = csInfoRepository.infoByMobile(param.getMobile());
        Long id = info == null ? 0 : info.getId();
        if(id == 0){
            id = csInfoRepository.create(param.getMobile(), param.getRegisterSource().getCode());
        }
        // 保证手机号和openid 唯一
        csWxInfoRepository.handleOpenidMobileUnique(param.getMobile(), param.getOpenid(), param.getAppId());

        CsWxInfo wxInfo = csWxInfoRepository.infoByMobileOpenid(param.getMobile(), param.getOpenid(), param.getAppId());
        if(wxInfo == null){
            wxInfo = new CsWxInfo();
            wxInfo.setAppId(param.getAppId());
            wxInfo.setMobile(param.getMobile());
            wxInfo.setOpenid(param.getOpenid());
            wxInfo.setUnionid(param.getUnionid());
            wxInfo.setAvatarUrl(param.getAvatarUrl());
            wxInfo.setNickName(param.getNickName());
            csWxInfoRepository.save(wxInfo);
        }else{
            CsWxInfo model = new CsWxInfo();
            model.setId(wxInfo.getId());
            model.setDelFlg(Integer.valueOf(DelFlgEnum.NORMAL.getCode()));
            csWxInfoRepository.updateById(model);
        }

        CsWxInfoDTO result = csInfoConvert.getCsWxInfoDTO(wxInfo);
        result.setInfoId(id);
        return result;
    }
}
